import React, { useState } from 'react';
import styled from 'styled-components';
import { motion } from 'framer-motion';
import { colors, spacing, typography } from '../styles/variables';
import { Card, Title, Paragraph, Button, TextArea, Input, Flex, Grid } from '../styles/components';
import { interpretDream } from '../services/dreamApi';
import { logInfo, logError, logDebug, logWarning } from '../logger';

const DreamHeader = styled(motion.div)`
  text-align: center;
  padding: ${spacing.xl} 0;
  margin-bottom: ${spacing.xl};
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
`;

const SearchSection = styled(Card)`
  max-width: 800px;
  margin: 0 auto;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  padding: 30px;
  border-radius: 12px;
  margin-bottom: 30px;
  box-shadow: 0 8px 30px rgba(0,0,0,0.12);
  border: 1px solid rgba(0,0,0,0.05);
`;

const SearchForm = styled.form`
  display: flex;
  gap: ${spacing.md};
  margin-bottom: ${spacing.lg};
  
  @media (max-width: 768px) {
    flex-direction: column;
  }
`;

const DreamCategories = styled.div`
  display: flex;
  flex-wrap: wrap;
  gap: ${spacing.sm};
  margin-top: ${spacing.lg};
`;

const CategoryTag = styled(Button)`
  background: ${props => props.selected ? colors.gradientGold : colors.backgroundSecondary};
  color: ${props => props.selected ? colors.background : colors.textPrimary};
  border: 1px solid ${props => props.selected ? 'transparent' : colors.border};
  padding: ${spacing.sm} ${spacing.md};
  font-size: ${typography.fontSize.sm};
`;

const PopularDreams = styled.div`
  margin-top: ${spacing.xl};
`;

const DreamList = styled.div`
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: ${spacing.md};
  margin-top: ${spacing.md};
`;

const DreamItem = styled(Card)`
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-3px);
    box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
  }
`;

const DreamTitle = styled.h4`
  color: ${colors.textPrimary};
  margin-bottom: ${spacing.sm};
`;

const Description = styled.p`
  text-align: center;
  color: #666;
  margin-bottom: 30px;
`;

const ErrorMessage = styled.div`
  color: #e74c3c;
  text-align: center;
  padding: 10px;
`;

const ResultSection = styled(motion.div)`
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 8px 30px rgba(0,0,0,0.12);
  max-width: 800px;
  margin: 0 auto;
  border: 1px solid rgba(0,0,0,0.05);
`;

const ResultTitle = styled.h2`
  color: #333;
  margin-bottom: 20px;
  text-align: center;
`;

const Interpretation = styled.p`
  font-size: 18px;
  line-height: 1.6;
  color: #444;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0,0,0,0.05);
  border-left: 4px solid #667eea;
`;

const LuckyInfo = styled.div`
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
`;

const LuckyItem = styled.div`
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  padding: 20px;
  border-radius: 12px;
  text-align: center;
  flex: 1;
  min-width: 120px;
  box-shadow: 0 4px 15px rgba(0,0,0,0.08);
  border: 1px solid rgba(0,0,0,0.05);
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 6px 20px rgba(0,0,0,0.12);
  }
`;

const Advice = styled.p`
  font-size: 16px;
  line-height: 1.6;
  color: #27ae60;
  padding: 15px;
  background: white;
  border-radius: 8px;
  border-left: 4px solid #27ae60;
`;

const PositiveSection = styled.div`
  margin-top: 25px;
  padding-top: 20px;
  border-top: 1px dashed #ddd;
`;

const SectionTitle = styled.h3`
  color: #333;
  margin-bottom: 15px;
  text-align: center;
`;

const Metaphor = styled.p`
  font-size: 16px;
  line-height: 1.6;
  color: #8e44ad;
  padding: 15px;
  background: white;
  border-radius: 8px;
  text-align: center;
  font-style: italic;
`;

const Encouragement = styled.p`
  font-size: 18px;
  font-weight: bold;
  color: #e74c3c;
  text-align: center;
  margin: 20px 0;
`;

const Prediction = styled.p`
  font-size: 16px;
  color: #2980b9;
  text-align: center;
  padding: 15px;
  background: white;
  border-radius: 8px;
`;

const MoodInfo = styled.div`
  display: flex;
  justify-content: space-around;
  margin: 20px 0;
  flex-wrap: wrap;
  gap: 10px;
`;

const MoodItem = styled.div`
  background: white;
  padding: 12px;
  border-radius: 8px;
  text-align: center;
  flex: 1;
  min-width: 100px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.05);
`;

const categories = [
  '人物', '动物', '自然', '建筑', '物品', '情感', '颜色', '数字'
];

const popularDreams = [
  { title: '梦见蛇', summary: '象征变化与转化，可能预示生活中的重大转变' },
  { title: '梦见水', summary: '代表情感世界，清澈的水通常象征好的情感状态' },
  { title: '梦见飞翔', summary: '表示渴望自由，或是近期压力得到释放' },
  { title: '梦见考试', summary: '反映内心焦虑，可能是对某件事情缺乏信心' },
  { title: '梦见死亡', summary: '象征结束与新生，不代表真实的死亡' },
  { title: '梦见牙齿脱落', summary: '可能表示担心外貌或害怕失去控制' }
];

const sampleInterpretations = [
  {
    dream: '梦见蛇',
    interpretation: '梦见蛇通常象征着变化与转化。蛇在许多文化中都代表着智慧、重生和治愈的力量。这个梦境可能预示着您生活中即将发生重要的转变，这些变化虽然可能让您感到不安，但最终会带来积极的结果。\n\n如果蛇是友好的，这可能意味着您正在接受自己的某些方面或者正在经历积极的变化。如果蛇是威胁性的，这可能反映了您对某些情况或人的恐惧或担忧。'
  },
  {
    dream: '梦见水',
    interpretation: '水在梦境中通常代表您的情感世界。梦见水的状态可以反映您当前的情感状态。\n\n清澈平静的水通常象征着内心的平和与满足感；浑浊或汹涌的水可能表示情绪上的困扰或压力。梦见自己在水中游泳可能意味着您正在努力处理复杂的情感问题。'
  }
];

function DreamInterpreter() {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('');
  const [dreamDescription, setDreamDescription] = useState('');
  const [interpretation, setInterpretation] = useState('');
  const [result, setResult] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleSearch = (e) => {
    e.preventDefault();
    // 模拟搜索结果
    if (searchTerm) {
      const result = sampleInterpretations.find(item => 
        item.dream.includes(searchTerm)
      );
      
      if (result) {
        setInterpretation(result.interpretation);
      } else {
        setInterpretation(`关于"${searchTerm}"的解梦信息暂时没有找到。请尝试其他关键词或详细描述您的梦境。`);
      }
    }
  };

  const handleAnalyze = async (e) => {
    e.preventDefault();
    logDebug('开始处理AI解梦表单提交');
    
    if (!dreamDescription.trim()) {
      logWarning('用户尝试提交空的梦境描述');
      setError('请输入梦境描述');
      return;
    }
    
    setLoading(true);
    setError('');
    setResult(null);
    
    try {
      logInfo('开始解梦分析', { dreamDescription });
      logDebug('调用interpretDream API');
      const data = await interpretDream(dreamDescription);
      logDebug('API调用成功，设置解梦结果', { 
        resultKeys: Object.keys(data),
        hasInterpretation: !!data.interpretation,
        hasMetaphor: !!data.metaphor
      });
      setResult(data);
      logInfo('解梦分析完成');
    } catch (err) {
      logError('解梦分析失败', { error: err.message, dreamDescription });
      setError('解梦分析失败，请稍后重试');
    } finally {
      setLoading(false);
      logDebug('AI解梦请求处理完成');
    }
  };

  const selectPopularDream = (dreamTitle) => {
    setSearchTerm(dreamTitle);
    const result = sampleInterpretations.find(item => 
      item.dream === dreamTitle
    );
    
    if (result) {
      setInterpretation(result.interpretation);
    }
  };

  return (
    <>
      <DreamHeader>
        <Title>周公解梦</Title>
        <Paragraph center>描述您的梦境，获取专业的解梦分析</Paragraph>
      </DreamHeader>

      <SearchSection
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
      >
        <form onSubmit={handleSearch}>
          <SearchForm>
            <Input
              type="text"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              placeholder="搜索梦境关键词，如：蛇、水、飞翔..."
              style={{ flex: 1 }}
              whileFocus={{ scale: 1.02 }}
              transition={{ type: "spring", stiffness: 300 }}
            />
            <Button 
              variant="primary" 
              type="submit"
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
              transition={{ type: "spring", stiffness: 400, damping: 17 }}
            >
              搜索
            </Button>
          </SearchForm>
        </form>

        <Paragraph secondary>或选择梦境类别：</Paragraph>
        <DreamCategories>
          {categories.map((category, index) => (
            <CategoryTag
              key={index}
              selected={selectedCategory === category}
              onClick={() => setSelectedCategory(category)}
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
              transition={{ type: "spring", stiffness: 400, damping: 17 }}
            >
              {category}
            </CategoryTag>
          ))}
        </DreamCategories>
      </SearchSection>

      <SearchSection
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5, delay: 0.2 }}
      >
        <Title size="md">AI智能解梦</Title>
        <Description>输入你的梦境，我们将为你提供积极的心理暗示和正能量解读</Description>
        
        <form onSubmit={handleAnalyze}>
          <TextArea
            value={dreamDescription}
            onChange={(e) => setDreamDescription(e.target.value)}
            placeholder="请尽可能详细地描述您的梦境，包括场景、人物、情节发展等..."
            whileFocus={{ scale: 1.02 }}
            transition={{ type: "spring", stiffness: 300 }}
          />
          <Flex justify="flex-end" style={{ marginTop: spacing.md }}>
            <Button 
              variant="primary" 
              type="submit" 
              disabled={loading}
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
              transition={{ type: "spring", stiffness: 400, damping: 17 }}
            >
              {loading ? '分析中...' : '智能解梦'}
            </Button>
          </Flex>
        </form>
        {error && (
          <motion.div 
            style={{ color: 'red', marginTop: '10px' }}
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ duration: 0.3 }}
          >
            {error}
          </motion.div>
        )}
      </SearchSection>

      <PopularDreams>
        <Title size="md">热门梦境</Title>
        <DreamList>
          {popularDreams.map((dream, index) => (
            <DreamItem 
              key={index}
              onClick={() => selectPopularDream(dream.title)}
              as={motion.div}
              whileHover={{ y: -5 }}
              whileTap={{ scale: 0.98 }}
            >
              <DreamTitle>{dream.title}</DreamTitle>
              <Paragraph secondary>{dream.summary}</Paragraph>
            </DreamItem>
          ))}
        </DreamList>
      </PopularDreams>

      {/* 原有搜索结果展示 */}
      {interpretation && !result && (
        <Card>
          <Title size="md">解梦结果</Title>
          <Paragraph style={{ whiteSpace: 'pre-line' }}>
            {interpretation}
          </Paragraph>
          <Flex justify="center" style={{ marginTop: spacing.lg }}>
            <Button variant="primary">
              🔖 保存解读
            </Button>
          </Flex>
        </Card>
      )}

      {/* 新增的AI解梦结果展示 */}
      {result && (
        <ResultSection
          initial={{ opacity: 0, y: 30 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6 }}
        >
          <motion.h3
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ delay: 0.2 }}
          >
            解梦结果
          </motion.h3>
          <Interpretation
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ delay: 0.3 }}
          >
            {result.interpretation}
          </Interpretation>
          
          {result.metaphor && (
            <motion.p
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ delay: 0.4 }}
            >
              ✨ {result.metaphor}
            </motion.p>
          )}
          
          <motion.div 
            style={{ display: 'flex', gap: '20px', marginBottom: '20px' }}
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ delay: 0.5 }}
          >
            <MoodItem>
              <strong>心情指数</strong>
              <div>{result.mood}</div>
            </MoodItem>
            <MoodItem>
              <strong>能量指数</strong>
              <div>{result.energy}</div>
            </MoodItem>
            <MoodItem>
              <strong>自信指数</strong>
              <div>{result.confidence}</div>
            </MoodItem>
          </motion.div>

          <motion.div 
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ delay: 0.6 }}
          >
            <SectionTitle>积极心理暗示</SectionTitle>
            <Encouragement>🌟 {result.encouragement}</Encouragement>
          </motion.div>
          
          <motion.div 
            style={{ display: 'flex', gap: '15px', flexWrap: 'wrap' }}
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ delay: 0.7 }}
          >
            <LuckyItem
              whileHover={{ y: -5 }}
              transition={{ type: "spring", stiffness: 300 }}
            >
              <strong>幸运数字</strong>
              <div style={{ fontSize: '24px', color: '#667eea', marginTop: '5px' }}>
                {result.luckyNumber}
              </div>
            </LuckyItem>
            <LuckyItem
              whileHover={{ y: -5 }}
              transition={{ type: "spring", stiffness: 300 }}
            >
              <strong>幸运颜色</strong>
              <div style={{ fontSize: '18px', color: '#764ba2', marginTop: '5px' }}>
                {result.luckyColor}
              </div>
            </LuckyItem>
          </motion.div>

          <motion.p
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ delay: 0.8 }}
          >
            <Advice>💡 建议: {result.advice}</Advice>
          </motion.p>
          
          <motion.p
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ delay: 0.9 }}
          >
            <Prediction>🔮 今日运势: {result.prediction}</Prediction>
          </motion.p>
        </ResultSection>
      )}
      
      {error && <ErrorMessage>{error}</ErrorMessage>}
    </>
  );
}

export default DreamInterpreter;